package com.controller.contribute;
import com.domain.*;
import com.server.CommentService;
import com.server.ContributeService;
import com.server.DocumentService;
import com.server.ReplyService;
import org.apache.ibatis.annotations.Param;
import org.springframework.http.HttpHeaders;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;
import java.io.File;
import java.io.FileInputStream;
import java.io.InputStream;
import java.util.Date;
import java.util.List;

@Controller
@RequestMapping(value = "contribute")
public class contributeController {

    @Resource(name = "contributeService")
    private ContributeService contributeService;

//    @Resource(name="documentService")
//    private DocumentService documentService;

    //通用页面跳转控制器
    @RequestMapping(value = "/{formName}")
    public String f(@PathVariable String formName){
        return formName;
    }

     @Resource(name="replyService")
    private ReplyService replyService;

    @Resource(name="documentService")
    private DocumentService documentService;

    @Resource(name="commentService")
    private CommentService commentService;

    //显示所有贡献
    @RequestMapping(value = "/space-contribute")
    public String showContribute(Model model, HttpServletRequest request,
                                 HttpSession session,@RequestParam(value = "page",defaultValue = "1")int page,
                                 @RequestParam(value = "pageSize",defaultValue = "8")int pageSize)throws  Exception{
        Space space=(Space) session.getAttribute("space");
        int space_id=space.getId();
        System.out.println("进入/space-contribute----space_id========"+space_id);
        User user=(User)session.getAttribute("user");
        session.setAttribute("user",user);
        String username=user.getUsername();
        model.addAttribute("username",username);
        List<Contribute> contributelist=contributeService.showContribute(page,pageSize,space_id);
        System.out.println("全部=========="+contributelist.size());
        //已接收
        List<Contribute> contributeList2=contributeService.showYContribute(space_id);
        //获取文件
        List<Document> flist=documentService.findAllFileByPage(space_id,page,pageSize);
        model.addAttribute("flist",flist);
        int fSize=0;
        for (int s=0;s<flist.size();s++){
            fSize++;
        }
        List<Contribute> contributeList3=contributeService.showUNContribute(space_id);
        List<Contribute> contributeList4=contributeService.showDContribute(space_id);
        model.addAttribute("contributelist",contributelist);
        int contributeTotal=contributeService.showContributeTotal(space_id);
        session.setAttribute("ContributeTotal", contributeTotal);
        if(((contributeTotal)/pageSize)<1){
            model.addAttribute("pageTotal",1);
        }else{
            if((contributeTotal)%pageSize!=0){
                int pageTotal=new Integer((contributeTotal)/pageSize+1);
                model.addAttribute("pageTotal",pageTotal);
            }else{
                int pageTotal=new Integer((contributeTotal)/pageSize);
                model.addAttribute("pageTotal",pageTotal);
            }
        }
        if(contributeTotal==0){
            model.addAttribute("contributeTotal",0);
        }
        else{
            model.addAttribute("contributeTotal",contributeTotal);
        }
        model.addAttribute("currentPage",page);

        int list2=0;
        int list3=0;
        int list4=0;

        for(int i=0;i<contributeList2.size();i++){
            list2++;
        }
        for(int j=0;j<contributeList3.size();j++){
            list3++;
        }
        for (int s=0;s<contributeList4.size();s++){
            list4++;
        }

        model.addAttribute("list2",list2);
        model.addAttribute("list3",list3);
        model.addAttribute("list4",list4);
        return "space-contribute";
    }

    //根据贡献id显示贡献
    @RequestMapping(value = "/space-contribute-show")
    public String showContributeById(@RequestParam("id") Integer id, Model model, HttpSession session,
                                     @RequestParam(value = "page",defaultValue = "1")int page,
                                     @RequestParam(value = "pageSize",defaultValue = "8")int pageSize)throws  Exception{
        System.out.println("****进入/space-contribute-show*****");
        System.out.println("文件id===="+id);
        //根据贡献id显示贡献信息
        Space space=(Space) session.getAttribute("space");
        int space_id=space.getId();
        Contribute contribute=contributeService.showContributeById(id,space_id);
        System.out.println("session空间id========="+space_id);
        User user=(User)session.getAttribute("user");
        String username=user.getUsername();
        model.addAttribute("username",username);
        //获取文件
        List<Document> flist=documentService.showDocumentById(id);
        for(int i=0;i<flist.size();i++){
            System.out.println("文件详情====="+flist.get(i).toString());
        }


    	List<Reply> replyList=replyService.selectAllReply();
        int total=commentService.selectCommentTotalByContributeId(id);
        List<Comment> commentList=commentService.selectCommentAndPageLimitById(id,page,pageSize);
        model.addAttribute("flist",flist);
        session.setAttribute("contribute",contribute);
        model.addAttribute("commentList",commentList);
        model.addAttribute("replyList",replyList);
        return "space-contribute-show";
    }



        @RequestMapping(value="/goToComment")
    public String goToComment(Integer contribute_id,Comment comment){
        System.out.println("话题id:"+contribute_id);
        System.out.println("发布者id:"+comment.getAuthor_id());
        System.out.println("内容:"+comment.getContent());
        Date date=new Date();
        comment.setCreatedate(date);
        comment.setResource_id(2);
        comment.setMember_id(1);
        comment.setContribute_id(contribute_id);
        int i=commentService.addComment(comment);
        System.out.println("成功添加的"+i+"条评论");
        return "redirect:space-contribute-show?id="+contribute_id+"";
    }

    @RequestMapping(value="/deleteComment")
    public String deleteComment(Integer comment_id,int contribute_id){
        System.out.println("要删除的评论id为"+comment_id);
        commentService.deleteCommentById(comment_id);
        return "redirect:space-contribute-show?id="+contribute_id+"";
    }

    @RequestMapping(value="/deleteReply")
    public String deleteReply(int reply_id,Integer contribute_id){
        System.out.println("要删除的回复id为"+reply_id);
        int i=replyService.deleteReplyById(reply_id);
        System.out.println("成功删除了"+i+"条评论");
        return "redirect:space-contribute-show?id="+contribute_id+"";
    }

    @RequestMapping(value="/reply",method = RequestMethod.POST)
    public String replyComment(Integer contribute_id,Integer comment_id,Integer member_id,Reply reply) {
        System.out.println("话题id:"+contribute_id);
        System.out.println("回复的话题id:"+comment_id);
        System.out.println("回复内容:"+reply.getContent());
        Date date=new Date();
        reply.setCreatedate(date);
       // reply.setId(1);
        System.out.println("回复内容:"+reply.getId());
        reply.setAuthor_id(1);
        //回复给那位成员:
        System.out.println("回复的成员id=="+member_id);
        reply.setMember_id(member_id);
        reply.setComment_id(comment_id);
        replyService.addReply(reply);
        return "redirect:space-contribute-show?id="+contribute_id+"";
    }

    @RequestMapping(value="download")
    public ResponseEntity<byte[]> download(@RequestParam("id") Integer id, @RequestParam("filename") String filename,
                                           @RequestParam("downloadcount") Integer downloadcount,
                                           HttpSession session, HttpServletRequest request)throws Exception {
        downloadcount = downloadcount + 1;
        documentService.updateNum(id, downloadcount);

        //获取目录/路径
        String path = session.getServletContext().getRealPath("/filelist");
        //编码方法
        String downloadFileName = new String(filename.getBytes("ISO-8859-1"), "UTF-8");
        File file = new File(path + File.separator + downloadFileName);
        byte[] body = null;
        InputStream is = new FileInputStream(file);
        body = new byte[is.available()];
        is.read(body);
        HttpHeaders headers = new HttpHeaders();
        headers.add("Content-Disposition", "attchement;filename=" + file.getName());
        HttpStatus statusCode = HttpStatus.OK;
        ResponseEntity<byte[]> entity = new ResponseEntity<byte[]>(body, headers, statusCode);
        return entity;
    }

    //采纳贡献
    @RequestMapping(value = "/setAccept")
    public String setAccept(@Param("id")int id, HttpSession session){
        Space space= (Space) session.getAttribute("space");
        int space_id=space.getId();
        System.out.println("进入setAccept");
        System.out.println("采纳贡献的id=="+id);
        Contribute before_contribute=contributeService.showContributeById(id,space_id);
        int before_status=before_contribute.getStatus();
        System.out.println("该话题的当前状态："+before_status);
        if(before_status!=2) {
            before_contribute.setStatus(2);
            int i = contributeService.updateContributeById(before_contribute);
        }
        return "redirect:space-contribute?id="+id+"";
    }

    //关闭贡献
    @RequestMapping(value = "/setExit")
    public String setExit(@Param("id")int id, HttpSession session){
        Space space= (Space) session.getAttribute("space");
        int space_id=space.getId();
        System.out.println("进入setAccept");
        System.out.println("采纳贡献的id=="+id);
        Contribute before_contribute=contributeService.showContributeById(id,space_id);
        int before_status=before_contribute.getStatus();
        System.out.println("该话题的当前状态："+before_status);
        if(before_status!=3) {
            before_contribute.setStatus(3);
            int i = contributeService.updateContributeById(before_contribute);
        }
        return "redirect:space-contribute?id="+id+"";
    }


}
